<template>
  <div class="container-m">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
      <el-form-item :label="$t('已选择的服务')" prop="serviceId">
        <el-select v-model="ruleForm.serviceId" filterable :placeholder="$t('请选择服务')" style="width: 100%"
          @change="resetForm">
          <el-option-group style="width: 90vw" v-for="(group, key) in serviceList" :key="$t(key)" :label="$t(key)">
            <el-option class="option" v-for="item in group" :key="item.serviceId" :label="item.serviceId + ' ' + $t(item.serviceName)"
              :value="item.serviceId" />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item prop="serviceNumber" class="ccc">
        <template #label>
          <div class="c-01" style="position: relative;z-index: 2;">
            <div>IMEI</div>
            <div class="scan">
              <img src="@/assets/images/scan_03.png" alt="" />
              <span @click="cvClick('single')">{{ $t("扫码输入") }}</span>
              <span> | </span>
              <span @click="cvClick('batch')">{{ $t("批量扫码") }}</span>
            </div>
          </div>
        </template>
        <el-input type="textarea" v-model="ruleForm.serviceNumber" :rows="6" :placeholder="$t('请输入IMEI，换行可输入多个，手机端使用回车键进行换行')
          "></el-input>
      </el-form-item>
      <el-form-item :label="$t('订单备注') + '（' + $t('可选') + '）'" prop="desc">
        <el-input type="textarea" v-model="ruleForm.desc" :rows="2" :placeholder="$t('如客户信息、设备码')"></el-input>
      </el-form-item>
      <div class="r-02">
        <div> {{ $t("需要消耗积分") }}：<span>{{ ruleForm.jifen }}</span></div>
        <div class="ts">当前余额可提交{{ num }} 个</div>

      </div>
      <div class="r-03" :style="{ opacity: checked ? '1' : '.6' }" @click="submit">
        <img src="@/assets/images/submit_icon_03.png" alt="" />
        <span>{{ $t("提交订单") }}</span>
      </div>
      <div class="r-04">
        <el-checkbox v-model="checked">
          <span style="color: red; font-size: 14px">{{
            $t("我已查看服务说明并同意上述条款")
            }}</span>
        </el-checkbox>
      </div>
      <div class="r-05">
        <div class="btn">{{ $t("温馨提示") }}</div>
        <div class="t t1" v-html="descriptionTemplate"></div>
        <!-- <div class="t t1">
          {{ $t('设备型号以及是否打开了"查找我的iPhone";') }}
        </div>
        <div class="t t1">{{ $t("此服务不支持查询MacBook笔记本或电脑;") }}</div>
        <div class="t t1">{{ $t("如需查询MacBook请使用1127专用服务;") }}</div> -->
        <!-- <div class="t t2">
          {{ $t("本服务为实时服务,不支持取消或者退积分;") }}
        </div>
        <div class="t t3">
          {{ $t("本服务返回数据仅供参考;仅为手机维修从业者提供参考;") }}
        </div> -->
      </div>
    </el-form>
    <Cv :show="showCv" :mode="cvMode" @close-cv="closeCv" @scan-result="scanResult" @batch-scan-result="batchScanResult"
      v-if="showCv" />
  </div>
</template>

<script>
import apiService from "@/api/apiService";
import Cv from "@/views/Cv.vue";
import { mapGetters } from "vuex";

// import { isMobile, replace, getCurrentUser, isWx, hasEnt } from "@/utils";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "ServiceMobile",
  data() {
    return {
      //是否显示扫一扫
      showCv: false,
      allServiceList: [],
      serviceList: [],
      checked: false,
      // 扫码模式(single/batch)
      cvMode: 'single',
      ruleForm: {
        serviceId: "",
        desc: "",
        jifen: 0,
        serviceNumber: "",
      },
      rules: {
        serviceId: [
          { required: true, message: this.$t("请选择服务"), trigger: "change" },
        ],
        serviceNumber: [
          {
            required: true,
            message: this.$t(this.$t("请输入订单内容")),
            trigger: "blur",
          },
        ],
      },
      descriptionTemplate: "",
    };
  },
  watch: {
    "ruleForm.serviceId": {
      handler() {
        this.setJf();
      },
    },
  },
  components: {
    Cv,
  },
  computed: {
    ...mapGetters(["getUserInfo"]),
    num() {
      if (this.ruleForm.jifen == 0) {
        return 0
      } else {
        return Math.floor(this.getUserInfo.pointsBalance / this.ruleForm.jifen)
      }
    }
  },
  mounted() {
    this.getData();
    const { serviceId, mode } = this.$route.query;
    if (serviceId) {
      this.ruleForm.serviceId = serviceId;
    }

    if (mode) {
      this.cvClick(mode)
    }
  },
  methods: {
    resetForm() {
      this.ruleForm.serviceNumber = "";
      this.ruleForm.desc = "";
      this.checked = false;
    },
    getData() {
      apiService.get("/all-service", {}).then((res) => {
        this.allServiceList = res.data;
        this.serviceList = this.groupedByParent(res.data);
        // this.current = Object.keys(this.serviceList)[0]
        // this.serviceChildList = this.serviceList[this.current]
        this.setJf();
      });
    },
    groupedByParent(list) {
      return list.reduce((acc, item) => {
        const key = item.parent;
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(item);
        return acc;
      }, {});
    },
    setJf() {
      if (this.ruleForm.serviceId) {
        const obj = this.allServiceList.find(
          (u) => u.serviceId === this.ruleForm.serviceId
        );
        this.ruleForm.jifen = obj?.price || 0;

        this.descriptionTemplate = obj?.describtion ?? '';
      }
    },
    batchScanResult(val) {
      // 按换行符拆分成数组
      const serviceNumberArray = this.ruleForm.serviceNumber.split('\n').filter(line => line.trim() !== '');
      serviceNumberArray.push(val)
      this.ruleForm.serviceNumber = [...new Set(serviceNumberArray)].join('\n');
    },
    submit() {
      if (this.checked) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            apiService.post("/submit-order", { ...this.ruleForm }).then(() => {
              this.$message.success('操作成功')
              // this.$store.commit("setShowModal", "s");
              // this.checked = false;
              // this.ruleForm.serviceId = "";
              this.ruleForm.serviceNumber = "";
              this.ruleForm.desc = "";
              this.ruleForm.jifen = 0;
              this.$refs.ruleForm.clearValidate();
            });
          }
        });
      }
    },
    scanResult(val) {
      // this.checked = true;
      this.ruleForm.serviceNumber = val;
      // this.submit();
      this.closeCv();
    },
    closeCv() {
      this.showCv = false;
    },
    cvClick(mode) {
      this.cvMode = mode;
      this.showCv = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.c-01 {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .scan {
    display: flex;
    align-items: center;

    img {
      width: 0.2rem;
    }

    span {
      color: #7594fc;
      font-size: 0.14rem;
      padding-left: 5px;
    }
  }
}

.r-02 {
  font-size: 0.14rem;
  color: #666;

  span {
    color: #ff0000;
  }

  display: flex;
  align-items: center;
  justify-content: space-between;

  .ts {
    color: #5288e8;
  }
}

.r-03 {
  margin-top: 18px;
  cursor: pointer;
  height: 0.4rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: linear-gradient(to right, #5288e8, #105be0);
  color: #fff;

  img {
    margin-right: 10px;
  }
}

.r-04 {
  margin-top: 18px;
}

.r-05 {
  margin-top: 18px;

  .btn {
    font-size: 0.16rem;
    margin-block: 5px;
  }

  .t {
    &.t1 {
      color: #333;
      font-size: 0.14rem;
    }

    &.t2 {
      color: #5288e8;
      font-size: 0.14rem;
    }

    &.t3 {
      font-size: 0.16rem;
      color: red;
    }
  }
}

::v-deep .ccc .el-form-item__label {
  width: 100%;
}

::v-deep .el-form-item__label:before {
  display: none;
}
</style>
